<template>
  <div class="collapsible-section border border-gray-200 rounded-lg overflow-hidden">
    <!-- 标题栏 -->
    <div
      class="section-header bg-gray-50 px-4 py-3 border-b border-gray-200 cursor-pointer hover:bg-gray-100 transition-colors duration-200 flex items-center justify-between"
      @click="toggleCollapse"
    >
      <div class="flex items-center gap-3">
        <!-- 折叠图标 -->
        <div class="flex-shrink-0">
          <svg
            class="w-5 h-5 text-gray-500 transition-transform duration-200"
            :class="{ 'rotate-180': !isCollapsed }"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
          </svg>
        </div>
        
        <!-- 标题 -->
        <h3 class="text-lg font-semibold text-gray-800 m-0">{{ title }}</h3>
        
        <!-- 内容数量提示 -->
        <span
          v-if="itemCount > 0"
          class="text-sm text-gray-500 bg-gray-200 px-2 py-1 rounded-full"
        >
          {{ itemCount }} 项
        </span>
      </div>
      
      <!-- 操作按钮 -->
      <div class="flex items-center gap-2" @click.stop>
        <slot name="actions" />
      </div>
    </div>
    
    <!-- 内容区域 -->
    <Transition
      enter-active-class="transition-all duration-300 ease-out"
      enter-from-class="opacity-0 max-h-0"
      enter-to-class="opacity-100 max-h-screen"
      leave-active-class="transition-all duration-300 ease-in"
      leave-from-class="opacity-100 max-h-screen"
      leave-to-class="opacity-0 max-h-0"
    >
      <div v-if="!isCollapsed" class="section-content">
        <div class="p-4">
          <slot />
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
interface Props {
  title: string
  itemCount?: number
  defaultCollapsed?: boolean
  sectionId?: string
  externalState?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  itemCount: 0,
  defaultCollapsed: false,
  externalState: false
})

// 内部状态
const internalCollapsed = ref(props.defaultCollapsed)

// 使用外部状态管理
const { isCollapsed: externalIsCollapsed, toggleCollapse: externalToggleCollapse } = useCollapseState()

// 计算属性：使用外部状态还是内部状态
const isCollapsed = computed(() => {
  if (props.externalState && props.sectionId) {
    return externalIsCollapsed(props.sectionId)
  }
  return internalCollapsed.value
})

const toggleCollapse = () => {
  if (props.externalState && props.sectionId) {
    externalToggleCollapse(props.sectionId)
  } else {
    internalCollapsed.value = !internalCollapsed.value
  }
}

// 暴露方法给父组件
defineExpose({
  toggleCollapse,
  isCollapsed: readonly(isCollapsed)
})
</script>

<style scoped>
.section-content {
  overflow: hidden;
}

/* 确保过渡动画正常工作 */
.collapsible-section {
  transition: all 0.3s ease;
}
</style>
